package de.gof.ppstool.staticdata;

import static de.gof.ppstool.util.LogUtil.begin;
import static de.gof.ppstool.util.LogUtil.end;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import de.gof.ppstool.staticdata.db.IStaticDataVerwaltungDAO;
import de.gof.ppstool.staticdata.db.StaticData;
import de.gof.ppstool.util.GofUtil;

@Service(IStaticDataVerwaltung.NAME)
@Transactional
public class StaticDataVerwaltung implements IStaticDataVerwaltung,
		Serializable {
	private static final long serialVersionUID = -3074778112149123054L;
	private static final Log LOG = LogFactory.getLog(GofUtil.class);
	private static final boolean DEBUG = LOG.isDebugEnabled();
	@SuppressWarnings("unused")
	private static final boolean TRACE = LOG.isDebugEnabled();
	@SuppressWarnings("unused")
	@PersistenceContext
	private EntityManager em;
	@Autowired
	private IStaticDataVerwaltungDAO dao;

	public StaticDataVerwaltung() {
		super();
		LOG.debug("StaticDataVerwaltung set");
	}

	/**
	 * { @inheritDoc}
	 */
	@Transactional
	@Override
	public StaticData changeStaticData(StaticData sdata) {
		if (DEBUG)
			begin(LOG, sdata);

		if (sdata == null)
			return null;

		sdata = dao.changeStaticData(sdata);
		if (DEBUG)
			end(LOG, sdata);

		return sdata;
	}

	/**
	 * { @inheritDoc}
	 */
	@Transactional
	@Override
	public StaticData findStaticData(Long sDataId)
			throws StaticDataNotFoundException {
		if (DEBUG)
			begin(LOG, sDataId);

		StaticData sData = null;
		sData = dao.findStaticData(sDataId);
		if (DEBUG)
			end(LOG, sData);

		return sData;
	}

	/**
	 * Gets the current Period
	 * @return
	 * @throws StaticDataNotFoundException
	 */
	public String getCurrentPeriod() throws StaticDataNotFoundException {
		String period = null;
		StaticData sd = this.findStaticData(Long.valueOf(1));
		period = sd.getPeriod();
		return period;
	}

	/**
	 * Gets the storage costs of the last period (n-1)
	 * @return
	 * @throws StaticDataNotFoundException
	 */
	public String getStorageCosts() throws StaticDataNotFoundException {
		String period = null;
		StaticData sd = this.findStaticData(Long.valueOf(1));
		period = sd.getLagerkosten();
		return period;
	}

}
